package com.kl.seq;

import lombok.extern.slf4j.Slf4j;

/**
 * 确保线程2在线程1之前运行
 * 使用 wait/notify 的方式
 */
@Slf4j
public class SequenceTest {
    private boolean isThread2 = false;
    private final Object obj = new Object();

    public void m1() {
        synchronized (obj) {
            // 如果线程2没有运行过,isThread2标志位就是false,那么线程一进行等待
            while (!isThread2) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.info("线程1执行");
        }
    }

    public void m2() {
        synchronized (obj) {
            isThread2 = true;
            log.info("线程2执行");
            obj.notify(); //唤醒等待的线程1
        }
    }

    public static void main(String[] args) {
        SequenceTest sequenceTest = new SequenceTest();
        new Thread(sequenceTest::m1, "线程1").start();
        new Thread(sequenceTest::m2, "线程2").start();
    }
}